const App = getApp();
const qingxilist = require('../../utils/qingxilist.js')
const siteinfo = require('../../siteinfo.js')
const radioList = require('../../utils/radioList')

Page({
  data: {
    ...radioList,
    // 页面参数
    qingxilist: qingxilist,
    options: {},
    // 页面元素
    scrollTop: 0,
    index: 0,
    detail: {},
    IsGongshui: '',
    tuResult: true, //检测一下是不是有没有图片未传完
    XianChangZhaoPian: [],
    GongZuoZhaoPian: [],
    WenTiZhaoPian: [],
    qingkong: '',
    ErGongShuiChiShuiZhiJianCeShiJian: '',
    TianBiaoRiQi: '',
    ErGongSheShiQingXiShiJian: '',
    GuanWangShiYongShiJian: '',
    ErGongSheShiJianCeShiJian: '',
    ErGongJiaYaSheBeiTiaoYaShiJian: '',
    YouZhiYongShuiShiJian: '',
    ErGongSheShiQingXiJiGou: '',
    ErGongXingShi: '', //二供形式，用于检测是否无负压供水
    LvHuaYongShui: '', //绿化水，用户检测是否中水
    // XiaoQuleiXing:'',//小区类型
    $data: {},
    qingkongList: [], //搜索的机构的list
    XiaoQuMingChengList: [],
    isBengfang: false,
    isShuichi: false,
    shuichiListT: [],
    shuichiListD: [],
    bengfangList: [],
    bengfangN: {},
    shuichiN: {},
    arr2:[],
    isEdit:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.setData({
      SYId:options.id
    })
    this.getDetail(options.id)
  },

  getDetail(e){
    let _this = this
    App._get("GetXiaoQuXunChaInfo",{id:e,userId:wx.getStorageSync('user_id')?wx.getStorageSync('user_id'):''},(res2)=>{
      let res= res2.xiaoQuXunCha
      var  arr = res.LouCeng?res.LouCeng.split( ',' ):[];
      var arr2 = []
      for( let i in _this.data.LouCengGaoDuList){
        for(let j in arr){
          if(_this.data.LouCengGaoDuList[i].value == arr[j]){
            arr2[i]=parseInt(i)
          }
        }
      }
      _this.setData({
        detail:res,
        XiaoQuMingCheng:res.XiaoQuMingCheng,
        ErGongSheShiJianCeShiJian:res.ErGongSheShiJianCeShiJian,
        TianBiaoRiQi:res.TianBiaoRiQi,
        ErGongSheShiQingXiShiJian:res.ErGongSheShiQingXiShiJian,
        GuanWangShiYongShiJian:res.GuanWangShiYongShiJian,
        ErGongSheShiJianCeShiJian:res.ErGongSheShiJianCeShiJian,
        ErGongJiaYaSheBeiTiaoYaShiJian:res.ErGongJiaYaSheBeiTiaoYaShiJian,
        YouZhiYongShuiShiJian:res.YouZhiYongShuiShiJian,
        ErGongSheShiQingXiJiGou:res.ErGongSheShiQingXiJiGou,
        XianChangZhaoPian:res.XianChangZhaoPian?res.XianChangZhaoPian.split( ',' ):[],
        GongZuoZhaoPian:res.GongZuoZhaoPian?res.GongZuoZhaoPian.split( ',' ):[],
        WenTiZhaoPian:res.WenTiZhaoPian?res.WenTiZhaoPian.split( ',' ):[],
        IsGongshui:res.ErCiGongShui,
        YongZhiYongShuiYiLiXiang:res.YongZhiYongShuiYiLiXiang,
        LouCeng:arr,
        arr2:arr2,
        shuichiListT: res2.shuichiListT,
        shuichiListD:res2.shuichiListD,
        bengfangList:res2.bengfangList,
      })
    })
  },
  radioChange(e) {
    let _this = this
    if (e.target.dataset.name) {
      let data = {}
      data[e.target.dataset.name] = e.detail.value
      _this.setData(data)
    }
  },

  searchQingkong(e){
    let _this = this;
    App._get('GetQingXiJiGou',{name:e.detail.value},(res)=>{
      console.log(res)
      if(res.length === 0){
        res = [{Name:'暂无数据'}]
      }
      _this.setData({
        qingkongList:res
      })
    })
  },
  searchXiaoQuMingCheng(e){
    let _this = this;
    App._get('GetXiaoQuInfo',{name:e.detail.value},(res)=>{
      console.log(res)
      if(res.length === 0){
        res = [{Name:'暂无数据'}]
      }
      _this.setData({
        XiaoQuMingChengList:res
      })
    })
  },
  selectQingkong(e){
    this.setData({
      qingkongList:[],
      ErGongSheShiQingXiJiGou:e.currentTarget.dataset.name
    })
  },
  selectXiaoQuMingCheng(e) {
    let _this = this
    console.log(_this.data.XiaoQuMingChengList[e.currentTarget.dataset.index],'这是选择的信息')
    var  arr = _this.data.XiaoQuMingChengList[e.currentTarget.dataset.index].LouCeng?_this.data.XiaoQuMingChengList[e.currentTarget.dataset.index].LouCeng.split( ',' ):[];
    var arr2 = []
    for( let i in _this.data.LouCengGaoDuList){
      for(let j in arr){
        if(_this.data.LouCengGaoDuList[i].value == arr[j]){
          arr2[i]=parseInt(i)
        }
      }
    }
    this.setData({
      XiaoQuMingCheng: e.currentTarget.dataset.name,
      detail: Object.assign(_this.data.detail,_this.data.XiaoQuMingChengList[e.currentTarget.dataset.index]),
      XiaoQuMingChengList: [],
      LouCeng:arr,
      arr2:arr2,
    })
  },
  formSubmit(e) {
    var _this = this
    let data = {
      ...e.detail.value
    }
    if(_this.data.loading){
      return
    }
    try{

    if(!_this.data.tuResult){
      wx.showModal({
        cancelColor: 'cancelColor',
        showCancel:false,
        title:'',
        content:'图片上传中，请稍后提交'
      })
      return
    }
    if (data.XinYongDaiMa.length != "18") {
      wx.showModal({
        showCancel: false,
        title: '信用代码必须为18位'
      })
      return
    }
    _this.setData({
      loading:true
    })
    data.id = this.data.SYId
    data.ErGongSheShiJianCeShiJian = this.data.ErGongSheShiJianCeShiJian
    data.TianBiaoRiQi = this.data.TianBiaoRiQi
    data.ErGongSheShiQingXiShiJian = this.data.ErGongSheShiQingXiShiJian
    data.GuanWangShiYongShiJian = this.data.GuanWangShiYongShiJian
    data.ErGongSheShiJianCeShiJian = this.data.ErGongSheShiJianCeShiJian
    data.ErGongJiaYaSheBeiTiaoYaShiJian = this.data.ErGongJiaYaSheBeiTiaoYaShiJian
    // data.ErGongSheShiQingXiJiGou = this.data.qingxilist[_this.data.index]
    data.YouZhiYongShuiShiJian = this.data.YouZhiYongShuiShiJian
    data.XianChangZhaoPian = this.data.XianChangZhaoPian.join(",")
    data.GongZuoZhaoPian = this.data.GongZuoZhaoPian.join(",")
    data.WenTiZhaoPian = this.data.WenTiZhaoPian.join(",")
    data.shuichiListT = this.data.shuichiListT
    data.shuichiListD = this.data.shuichiListD
    data.bengfangList = this.data.bengfangList
    data.LouCeng =  data.LouCeng.join(',')
    wx.showLoading({
      title: '提交中',
    })
  }
    catch(e){
      wx.showModal({
        cancelColor: 'cancelColor',
        showCancel:false,
        title:'错误',
        content:'e'
      })
    }
    App._post_form(e.detail.target.dataset.xingwei == "tijiao"?'XiaoQuXunChaShenHe':'SaveXiaoQuXunCha',data, (res) => {
      wx.showModal({
        title: res,
        showCancel: false,
        complete: () => {
          // wx.navigateBack()
          _this.setData({
            loading:false
          })
        }
      })
    },()=>{},()=>{
      wx.hideLoading()
    })
  },

  add(e) { //添加水池或者是水泵
    let _this = this
    if (e.currentTarget.dataset.name === "shuichi") {
      if (e.currentTarget.dataset.leixing === "天面生活水池") {
        if (e.currentTarget.dataset.index !== undefined) {
          let shuichiN = {}
          shuichiN = _this.data.shuichiListT[e.currentTarget.dataset.index]
          shuichiN.index = e.currentTarget.dataset.index //给水池设定index下标
          _this.setData({
            isShuichi: true,
            shuichiN: shuichiN,
            isEdit:true
          })
        } else {
          _this.setData({
            isShuichi: true,
            shuichiN: {
              LeiXing: e.currentTarget.dataset.leixing,
              index: _this.data.shuichiListT.length
            }
          })
        }
      } else {
        if (e.currentTarget.dataset.index !== undefined) {
          let shuichiN = {}
          shuichiN = _this.data.shuichiListD[e.currentTarget.dataset.index]
          shuichiN.index = e.currentTarget.dataset.index //给水池设定index下标
          _this.setData({
            isShuichi: true,
            shuichiN: shuichiN,
            isEdit:true
          })
        } else {
          _this.setData({
            isShuichi: true,
            shuichiN: {
              LeiXing: e.currentTarget.dataset.leixing,
              index: _this.data.shuichiListD.length
            }
          })
        }
      }
    }
    if (e.currentTarget.dataset.name === "bengfang") {
      if (e.currentTarget.dataset.index !== undefined) { //修改
        let bengfangN = {} //初始化泵房
        bengfangN = _this.data.bengfangList[e.currentTarget.dataset.index] //加载泵房数据
        bengfangN.index = e.currentTarget.dataset.index //给泵房设定index下标
        var arr = bengfangN.ShengHuoBengLeiXing ? bengfangN.ShengHuoBengLeiXing.split(',') : [];
        var arr2 = []
        for (let i in _this.data.ShengHuoBengLeiXingList) { //处理泵房内的数组
          for (let j in arr) {
            if (_this.data.ShengHuoBengLeiXingList[i].value == arr[j]) {
              arr2[i] = parseInt(i)
            }
          }
        }
        _this.setData({
          isBengfang: true,
          bengfangN: bengfangN,
          arr2:arr2,
          isEdit:true
        })
      } else {
        _this.setData({
          isBengfang: true,
          bengfangN: {
            index: _this.data.bengfangList.length
          }
        })
      }
    }
  },
  cancel() {
    this.setData({
      isShuichi: false,
      isBengfang: false
    })
  },
  shuichisave(e) {
    let _this = this
    if (e.detail.LeiXing == "地下生活水池") {
      console.log('di')
      let arr = _this.data.shuichiListD;
      arr[e.detail.index] = e.detail;
      _this.setData({
        shuichiListD: arr
      })
    } else if (e.detail.LeiXing == "天面生活水池") {
      console.log('tian')
      let arr = _this.data.shuichiListT;
      arr[e.detail.index] = e.detail;
      _this.setData({
        shuichiListT: arr
      })
    } else {
      App.showError('保存失败，水池类型出错')
    }
    this.setData({
      isShuichi: false
    })
  },
  bengfangsave(e) {
    console.log(e)
    let _this = this
    let arr = _this.data.bengfangList;
    arr[e.detail.index] = e.detail;
    _this.setData({
      bengfangList: arr
    })
    this.setData({
      isBengfang: false
    })
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage() {
    let _this = this;
    return {
      title: _this.data.detail.Name,
      path: `/pages/xiaoqu/idnex`,
    };
  },
  bindDateChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    console.log(typeof (e.detail.value))
    console.log(e.detail.value)
    this.setData({
      TianBiaoRiQi: e.detail.value
    })
  },
  bindDateErGongSheShiJianCeShiJian(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ErGongSheShiJianCeShiJian: e.detail.value
    })
  },
  bindDateErGongJiaYaSheBeiTiaoYaShiJian(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ErGongJiaYaSheBeiTiaoYaShiJian: e.detail.value
    })
  },
  bindDateChangeErGongSheShiQingXiShiJian(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ErGongSheShiQingXiShiJian: e.detail.value
    })
  },
  bindDateErGongSheShiJianCeShiJian(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ErGongSheShiJianCeShiJian: e.detail.value
    })
  },
  bindDateChangeGuanWangShiYongShiJian(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      GuanWangShiYongShiJian: e.detail.value
    })
  },
  bindDateChangeYouZhiYongShuiShiJian(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      YouZhiYongShuiShiJian: e.detail.value
    })
  },
  bindErGongSheShiQingXiJiGou(e){
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  radioChangeJinChuShuiGuanCaiZhi(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      JinChuShuiGuanCaiZhi: e.detail.value
    })
  },
  radioChangeErGongTianMianShuiChiCaiZhi(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ErGongTianMianShuiChiCaiZhi: e.detail.value
    })
  },
  radioChangeGuanGaiMoShi(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      GuanGaiMoShi: e.detail.value
    })
  },
  radioChangeJieShuiQiJuGuanXiaDanWei(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      JieShuiQiJuGuanXiaDanWei: e.detail.value
    })
  },
  radioChangeYongZhiYongShuiYiLiXiang(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      YongZhiYongShuiYiLiXiang: e.detail.value
    })
  },
  radioChangeErGongGuanLiPeiXun(e){
    console.log(e.detail.value)
    this.setData({
      ErGongGuanLiPeiXun: e.detail.value
    })
  },
  blurXinYongDaiMa(e) {
    if (e.detail.value.length != "18") {
      wx.showModal({
        showCancel: false,
        title: '信用代码必须为18位'
      })
    }
  },
  blurLianXiFangShi(e) {
    if (e.detail.value.length != "11") {
      wx.showModal({
        showCancel: false,
        title: '手机号必须为11位'
      })
    }
  },
  blurZuoji(e) {
    if (e.detail.value.length != "7" && e.detail.value.length != "8") {
      wx.showModal({
        showCancel: false,
        title: '座机号码只能为7位或者8位'
      })
    }
  },
  bindXianChangZhaoPian(){
    let _this =this
    var XianChangZhaoPianList = []
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        let arr = [];
        _this.setData({
          tuResult:false
        })
        for(let i in res.tempFiles){
         let promise = new Promise((rel,rej)=>{
          App.uploaFile('/api/UpLoadProcess',res.tempFiles[i].tempFilePath,(res2)=>{
            rel(siteinfo.siteroot+res2)
          })
         })
         arr.push(promise)
        }
        Promise.all(arr).then((result)=>{
          console.log(result,'图片上传完成')
          let arrList = []
          arrList = arrList.concat(_this.data.XianChangZhaoPian)
          arrList.push.apply(arrList,result)
          _this.setData({
            XianChangZhaoPian:arrList,
            tuResult:true
          })
        })
      }
    })
  },
  bindGongZuoZhaoPian(){
    let _this =this
    var GongZuoZhaoPianList = []
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        let arr = [];
        _this.setData({
          tuResult:false
        })
        for(let i in res.tempFiles){
         let promise = new Promise((rel,rej)=>{
          App.uploaFile('/api/UpLoadProcess',res.tempFiles[i].tempFilePath,(res2)=>{
            rel(siteinfo.siteroot+res2)
          })
         })
         arr.push(promise)
        }
        Promise.all(arr).then((result)=>{
          console.log(result,'图片上传完成')
          let arrList = []
          arrList = arrList.concat(_this.data.GongZuoZhaoPian)
          arrList.push.apply(arrList,result)
          _this.setData({
            GongZuoZhaoPian:arrList,
            tuResult:true
          })
        })
      }
    })
  },
  bindWenTiZhaoPian(){
    let _this =this
    var WenTiZhaoPianList = []
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        let arr = [];
        _this.setData({
          tuResult:false
        })
        for(let i in res.tempFiles){
         let promise = new Promise((rel,rej)=>{
          App.uploaFile('/api/UpLoadProcess',res.tempFiles[i].tempFilePath,(res2)=>{
            rel(siteinfo.siteroot+res2)
          })
         })
         arr.push(promise)
        }
        Promise.all(arr).then((result)=>{
          console.log(result,'图片上传完成')
          let arrList = []
          arrList = arrList.concat(_this.data.WenTiZhaoPian)
          arrList.push.apply(arrList,result)
          _this.setData({
            WenTiZhaoPian:arrList,
            tuResult:true
          })
        })
      }
    })
  },
  shanchu(e){
  //  e.target.name
  let _this = this 
   console.log(e)
   let arr = []
   arr = arr.concat(_this.data[e.target.dataset.name])
   arr.splice(e.target.dataset.index,1)
   this.setData(_this.setKeyAndValue(e.target.dataset.name,arr))

   
  },
  setKeyAndValue(key,value){
    var obj = {};
    console.log(key)
    obj[key]=value
    console.log(obj)
    return obj
    },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    // 获取首页数据
    wx.stopPullDownRefresh();
  }
  ,
  goBottom(){
    var obj=wx.createSelectorQuery();
    obj.selectAll('.container').boundingClientRect(function (rect) {
      console.log(rect[0].height)
      console.log(rect[0].width)
      wx.pageScrollTo({
        scrollTop: rect[0].height,
        duration:300
      });
  })
  obj.exec() ;
  },
  delete(e) {
    const _this = this;
    const index = e.detail.index
    console.log(e)
    switch (e.detail.LeiXing) {
      case "地下生活水池": _this.arrDelete('shuichiListD', index); break;
      case "天面生活水池": _this.arrDelete('shuichiListT', index); break;
      default: _this.arrDelete('bengfangList', index); break;
    }
    _this.cancel()
  },
  arrDelete(key, index) {
    let arr = []
    let _this = this
    arr = arr.concat(_this.data[key])
    arr.splice(index, 1)
    _this.setData(_this.setKeyAndValue(key, arr))
  }

});